package config

import (
	"bytes"
	"encoding/json"
	"sync"

	consulApi "github.com/hashicorp/consul/api"
	"github.com/spf13/viper"
	"github.com/zeromicro/go-zero/core/configcenter/subscriber"
)

type ConsulSubscriber struct {
	listeners []func()
	lock      sync.Mutex
	consulCli *consulApi.Client
	Path      string
}

func NewConsulSubscriber(address, path string) subscriber.Subscriber {
	config := &consulApi.Config{
		Address: address,
	}
	client, err := consulApi.NewClient(config)
	if err != nil {
		panic(err)
	}
	return &ConsulSubscriber{
		consulCli: client,
		Path:      path,
	}
}
func (s *ConsulSubscriber) AddListener(listener func()) error {
	s.lock.Lock()
	defer s.lock.Unlock()
	s.listeners = append(s.listeners, listener)
	return nil
}

func (s *ConsulSubscriber) Value() (string, error) {
	defaultConfig := viper.New()
	defaultConfig.SetConfigType("yaml")
	kvPair, _, err := s.consulCli.KV().Get(s.Path, nil)
	if err != nil {
		panic(err)
	}
	err = defaultConfig.ReadConfig(bytes.NewBuffer(kvPair.Value))
	if err != nil {
		panic(err)
	}
	settings := defaultConfig.AllSettings()
	marshal, _ := json.Marshal(settings)
	return string(marshal), nil
}
